<template>
  <div class="inventory-list-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerRightButton>
        <el-button
          class="g-ml8"
          v-btnPermission="'ECI_MONITORING_PLAN_ADD'"
          type="primary"
          @click="handleCreatePlan"
          ><CIcon type="c-xian-xinjian" class="g-mr4"></CIcon>创建监测计划</el-button
        >
      </template>
      <template #inventoryNameSlot="{ scope }">
        <CTableColumn
          :main-text="scope.row.organizationName"
          :sub-text="scope.row.inventoryName"
          :isLink="scope.row.status === InventoryStatusEnum.RELEASED && viewPermission"
          @link-click="handleFillPlan(scope.row)"
        ></CTableColumn>
      </template>
      <template #sendLogSlot="{ scope }">
        <CLink
          @click="handleOpenSendLogDialog(scope.row)"
          v-if="['RELEASED', 'CANCEL_RELEASED'].includes(scope.row.status)"
          >下发日志</CLink
        >
      </template>
      <template #statusSlot="{ scope }">
        <el-tag class="g-tag" :type="renderTag(scope.row.status)" v-if="scope.row.status">{{
          InventoryStatusMap[(scope.row as GetInventoryResult).status]
        }}</el-tag>
        <span v-else>-</span>
      </template>
      <template #opSlot="{ scope }">
        <CTableButtonGroup
          :buttons-config="getTableButtonsConfig(scope.row)"
          :show-more-num="3"
          isInclude
        />
      </template>
    </CPageTable>
    <SendLogDialog v-model:visible="sendLogVisible" :inventoryNo="sendLogInventoryNo" />
  </div>
</template>
<script lang="ts">
export default {
  name: 'InventoryList'
};
</script>
<script lang="ts" setup name="InventoryList">
import { computed, ref } from 'vue';
import { store } from '@/store';
import { CPageTable, useCPageTable } from '@/components/CPageTable';
import { useInventory } from './useInventory';
import { useMessage } from '@/hooks/useMessage';
import {
  publishInventory,
  inventoryNotesSave,
  deleteInventory,
  cancelRelease,
  copyInventory,
  generateInventoryFile
} from '@/apis/eci/inventory/inventory';
import type { GetInventoryResult } from '@/apis/eci/inventory/model/inventoryModel';
import { InventoryStatusEnum, InventoryStatusMap } from '@/constants/enum';
import { useExport } from '@/hooks/useExport';
import { useRouter } from 'vue-router';
import { CTableButtonGroup } from '@/components/CTable';
import { CTableColumn, TableButtonItem } from '@/components/CTable';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import SendLogDialog from './components/SendLogDialog/index.vue';
import { CLink } from '@/components/CLink/index';

const { createConfirm, createMessage } = useMessage();
const { searchForm, options } = useInventory();
const [registerPage, { refresh }] = useCPageTable(options);
const router = useRouter();
const { handleExportFile } = useExport();
// 创建监测计划
const handleCreatePlan = () => {
  router.push('/emissionInventory/plan');
};

// 填写/修改监测计划
function handleFillPlan(row: GetInventoryResult) {
  const detail_path = {
    path: '/emissionInventory/plan',
    query: {
      inventoryNo: row.inventoryNo
    }
  };
  router.push(detail_path);
}

// 发布监测计划
function handlePublishPlan(row: GetInventoryResult) {
  createConfirm(
    '确认发布监测计划？',
    '发布监测计划后，将生成活动数据填报任务，请仔细核对排放源。',
    {
      iconType: 'warning',
      btnType: 'primary',
      confirmButtonText: '发布'
    }
  ).then(async () => {
    try {
      await publishInventory(row.inventoryNo);
      createMessage.success('发布成功！');
      refresh();
    } catch (error) {
      console.log('error', error);
    }
  });
}
// 撤回发布
function handleCancel(row: GetInventoryResult) {
  createConfirm('确定撤回该监测计划吗？', '撤回后需要重新发布！', {
    iconType: 'warning'
  }).then(async () => {
    try {
      await cancelRelease(row.inventoryNo);
      createMessage.success('撤回成功！');
      refresh();
    } catch (error) {
      console.log('error', error);
    }
  });
}

// 删除监测计划
function handleDeletePlan(row: GetInventoryResult) {
  console.log('handleDeletePlan', row);
  createConfirm('提示', '删除后不可恢复，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      await deleteInventory(row.inventoryNo);
      createMessage.success('删除成功！');
      refresh();
    } catch (error) {
      console.log('error', error);
    }
  });
}

// 复制监测计划
async function handleCopyPlan(row: GetInventoryResult) {
  try {
    await copyInventory(row.inventoryNo);
    createMessage.success('复制成功！');
    refresh();
  } catch (error) {
    console.log('error', error);
  }
}

// 下载监测计划文件
function handleGeneratePlanFile(row: GetInventoryResult) {
  handleExportFile(generateInventoryFile, {
    inventoryNo: row.inventoryNo
  });
}

// 渲染tag
const renderTag = (status: GetInventoryResult['status']) => {
  switch (status) {
    case 'RELEASED':
      return 'success';
    default:
      return 'info';
  }
};

// 备注更新操作
function handleNoteUpdate(value: string, row: GetInventoryResult): Promise<boolean> {
  const params = {
    inventoryNo: row.inventoryNo,
    notes: value
  };
  return inventoryNotesSave(params);
}

const showEditPermission = computed(() => {
  const permissions = store.state.user.permissions;
  return permissions.includes('ECI_MONITORING_PLAN_EDIT');
});

const viewPermission = computed(() => {
  const permissions = store.state.user.permissions;
  return permissions.includes('ECI_MONITORING_PLAN_VIEW');
});

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: GetInventoryResult): TableButtonItem[] {
  // 未发布、已撤回
  if (['PROCESSING', 'CANCEL_RELEASED'].includes(row.status)) {
    return [
      {
        text: '发布',
        btnPermission: 'ECI_MONITORING_PLAN_SUBMIT',
        onClick: () => handlePublishPlan(row)
      },
      {
        text: '修改',
        btnPermission: 'ECI_MONITORING_PLAN_EDIT',
        onClick: () => handleFillPlan(row)
      },
      {
        text: '删除',
        btnPermission: 'ECI_MONITORING_PLAN_DELETE',
        onClick: () => handleDeletePlan(row)
      }
    ];
  } else if (row.status === InventoryStatusEnum.RELEASED) {
    return [
      {
        text: '复制',
        btnPermission: 'ECI_MONITORING_PLAN_COPY',
        onClick: () => handleCopyPlan(row)
      },
      {
        text: '生成监测计划文件',
        btnPermission: 'ECI_MONITORING_PLAN_DOWNLOAD',
        onClick: () => handleGeneratePlanFile(row)
      },
      {
        text: '撤回',
        btnPermission: 'ECI_MONITORING_PLAN_CANCEL',
        onClick: () => handleCancel(row)
      },
      {
        text: '删除',
        btnPermission: 'ECI_MONITORING_PLAN_DELETE',
        onClick: () => handleDeletePlan(row)
      }
    ];
  }
  return [];
}

const sendLogVisible = ref(false);
const sendLogInventoryNo = ref('');
function handleOpenSendLogDialog(row: GetInventoryResult) {
  sendLogVisible.value = true;
  sendLogInventoryNo.value = row.inventoryNo;
}

useKeepAliveRefresh(refresh);
</script>

<style lang="scss" scoped>
.inventory-list-container {
  // 表格边框颜色
  --el-border-color-lighter: #e4e7ed;
  .g-tag {
    &.el-tag--success {
      color: #37b17d;
      background-color: rgba(55, 177, 125, 0.06);
      border-color: #37b17d;
    }
  }
}
</style>
